package com.example.framework.common.util;

import com.example.framework.common.exception.ServiceException;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class GenericUtils {

    public static <T> Class<T> getGenericClass(Class<?> clazz, int index) {
//        return (Class<T>) TypeUtil.getTypeArgument(clazz, index);

        // 获取直接父类的类型
        Type genericSuperclass = clazz.getGenericSuperclass();
        return getGenericClass(genericSuperclass, index);
    }

    /**
     * 获取第n个接口的泛型类型
     */
    public static <T> Class<T> getGenericIntercaceClass(Class<?> clazz, int interfaceIndex, int argumentIndex) {
        Type genericSuperclass = clazz.getGenericInterfaces()[interfaceIndex];
        return getGenericClass(genericSuperclass, argumentIndex);
    }

    @SuppressWarnings("unchecked")
    private static <T> Class<T> getGenericClass(Type type, int index) {
        // 检查是否为参数化类型
        if (type instanceof ParameterizedType parameterizedType) {
            // 获取泛型的实际类型参数
            Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
            if (actualTypeArguments[index] instanceof Class<?> clazz) {
                return (Class<T>) clazz;
            }
        }

        throw ServiceException.of("无法获取泛型类型：未定义参数化类型或泛型类型不是 Class");
    }
}
